<?php


namespace app\backend\controller\v2;

use app\backend\validate\NavValidate;
use app\BaseController;
use app\common\model\Nav as NavModel;
use think\exception\ValidateException;

class Nav extends BaseController
{
    /**
     * 导航列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $model = NavModel::where('status', 1);
        $page = input('page/d', 1);
        $size = 10;
        $rows = $model->count();
        $maxPage = ceil($rows / $size);
        $data = $model->withAttr('image',function ($val,$data){
            return env('APP.YUMING').$val;
        })
            ->page($page,$size)
            ->select();
        return sucessMsg(200, '导航获取成功！', [
            'data' => $data,
            'page' => $page,
            'maxPage' => $maxPage,
            'rows' => $rows
        ]);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @return \think\Response
     */
    public function edit()
    {
        $id = input('get.id/d');
        if (empty($id)) {
            return errMsg(422, 'id不能为空');
        }
        $data = NavModel::where('id', $id)->find();
        if (!empty($data['image']))
            $data['image'] = env('APP.YUMING') . $data['image'];
        if (empty($data))
            return errMsg(422, '无效id');
        return sucessMsg(200, '获取成功！', $data);
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update()
    {
        $data = input();
        try {
            validate(NavValidate::class)->scene('update')->check($data);
            if (empty($data['image'])) {
                return errMsg(400, '请上传导航图片');
            }
            if(strpos($data['image'],'.com') !== false){
                $data['image'] = substr($data['image'],strpos( $data['image'],"m")+2);
            }
            $model = new NavModel();
            $cate = $model->where('id', $data['id'])->find();
            if ($cate->save($data)) {
                return sucessMsg(200, '修改成功！');
            }
            return errMsg(500, '修改失败！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }
}